package com.autotest.nore.controller;

import com.autotest.nore.common.exception.TokenEmptyException;
import com.autotest.nore.common.utils.PageUtils;
import com.autotest.nore.common.utils.Pager;
import com.autotest.nore.domain.Environment;
import com.autotest.nore.dto.EnvironmentDTO;
import com.autotest.nore.request.QueryRequest;
import com.autotest.nore.service.EnvironmentService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;


@RestController
@RequestMapping("/autotest/environment")
public class EnvironmentController {

    @Autowired
    private EnvironmentService environmentService;

    @PostMapping("/save")
    public void saveEnvironment(@RequestBody Environment environment, HttpServletRequest request) {
        HttpSession session = request.getSession(false); // 获取会话，如果不存在则返回null
        if (session == null || session.getAttribute("userName") == null) {
            throw new TokenEmptyException("用户未登录，请重新登录");
        }
        String userName = session.getAttribute("userName").toString();
        environment.setUpdateUser(userName);
        environmentService.saveEnvironment(environment);
    }

    @PostMapping("/delete")
    public void deleteEnvironment(@RequestBody Environment environment) {
        environmentService.deleteEnvironment(environment);
    }

    @GetMapping("/all/{projectId}")
    public List<Environment> getAllEnvironment(@PathVariable String projectId) {
        return environmentService.getAllEnvironment(projectId);
    }
    @GetMapping("/all/environmentName/{projectId}")
    public List<String> getAllEnvironmentName(@PathVariable String projectId){
        return environmentService.getAllEnvironmentName(projectId);
    }



    @PostMapping("/list/{goPage}/{pageSize}")
    public Pager<List<EnvironmentDTO>> getEnvironmentList(@PathVariable int goPage, @PathVariable int pageSize,
                                                          @RequestBody QueryRequest request) {
        Page<Object> page = PageHelper.startPage(goPage, pageSize, true);
        return PageUtils.setPageInfo(page, environmentService.getEnvironmentList(request.getProjectId(), request.getCondition()));
    }

}
